package com.woniuxy.controller;
/*
 * @author 幸琦林
 *
 */

import com.woniuxy.configuration.EasyTypeToken;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.SysRole;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import com.woniuxy.util.CommonUtil;
import com.woniuxy.util.RandomName;
import com.woniuxy.util.SendMessage;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/home")
public class LoginController {

    @Autowired
    UserService userService;

    //    保持当前用户的验证码
    String randomCode;
    //      是否手机验证码登录
    boolean loginFlage = false;

    //    通过账号密码登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> loginByAP(String account, String pwd, boolean remember) {

        Map<String, Object> map = new HashMap<>();
        Subject subject;
        try {
            //验证身份和登陆
            subject = SecurityUtils.getSubject();
            String md5pwd = new SimpleHash("MD5", pwd, account, 5).toString();
            System.out.println("/home/loginByAP:新密码" + new SimpleHash("MD5", md5pwd).toString());
            if (loginFlage) {
                EasyTypeToken typeToken = new EasyTypeToken(account);
                subject.login(typeToken);
                loginFlage = false;
            } else {
                EasyTypeToken token = new EasyTypeToken(account, md5pwd, remember);
                //验证成功进行登录操作
                subject.login(token);
            }
        } catch (IncorrectCredentialsException e) {
            map.put("code", 500);
            map.put("msg", "用户不存在或者密码错误");
            return map;
        } catch (LockedAccountException e) {
            map.put("code", 500);
            map.put("msg", "登录失败，该用户已被冻结");
            return map;
        } catch (AuthenticationException e) {
            map.put("code", 500);
            map.put("msg", "该用户不存在,请先注册");
            return map;
        } catch (Exception e) {
            map.put("code", 500);
            map.put("msg", "当前人太多，请稍后重试");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "登录成功");
//        如果用户只有唯一角色普通用户，则需要第一次认证
        List<SysRole> roles = CommonUtil.getCurrentUser().getRoles();
        System.out.println("登录权限判断：" + roles);
        System.out.println(CommonUtil.getCurrentUser());
        if (roles.size() == 1) {
            if (roles.get(0).getIdRole() == 1) {
                map.put("code", 3);
                map.put("msg", "需要认证");
            }
        }
        if (roles.size() < 1) {
            map.put("code", 3);
            map.put("msg", "需要认证");
        }
        return map;

    }

    //    账号密码注册操作
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Map<String, Object> registerUserByAP(String account, String pwd) {
        Map<String, Object> map = new HashMap<>();
        if (userService.userExist(account, 1)) {
            map.put("code", 500);
            map.put("msg", "账号已存在");
            return map;
        }
        User user = new User().setAccount(account).setPwd(pwd);
        int tempI = 0;
        map.put("code", 500);
        map.put("msg", "注册失败");
        if (account != null) {
            String md5pwd = new SimpleHash("MD5", user.getPwd(), user.getAccount(), 5).toString();
            user.setPwd(new SimpleHash("MD5", md5pwd).toString());
            user.setNickname(RandomName.getRandomName(3));
            int v = (int) (Math.random() * 3) + 1;
            user.setAvatar("../images/header" + v + ".jpg");

            System.out.println("LoginController:注册:" + user);
            tempI = userService.userRegister(user);
        }

        if (tempI == 1) {
//            注册完成登录
            return loginByAP(account, pwd, false);
        }
        return map;
    }

    //    手机号注册
    @RequestMapping(value = "/phoneRegister")
    public Map<String, Object> registerUserByPhone(String phoneNum, String myCode) {
        System.out.println("/home/phoneRegister:phone：-" + phoneNum);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "验证码错误!");
        int tempI = 0;
        if (randomCode.equals(myCode)) {
            User user = new User().setPhone(phoneNum);
            user.setNickname(RandomName.getRandomName(3));
            int v = (int) (Math.random() * 3) + 1;
            user.setAvatar("../images/header" + v + ".jpg");
            tempI = userService.userRegister(user);
            if (tempI == 1) {
                return loginByPhone(phoneNum, myCode, false);
            } else {
                map.put("msg", "注册异常，请重试!");
            }
        }
        return map;
    }

    //  验证码验证，看该用户是否已存在
    @RequestMapping(value = "/getCode", method = RequestMethod.GET)
    public Map<String, Object> regGetRandomCode(String phoneLogNum, boolean getType) {
        Map<String, Object> map = new HashMap<>();
        if (userService.userExist(phoneLogNum, 2)) {
            if (getType) {
                map.put("code", 10);
                map.put("msg", getRandomCode(phoneLogNum));
            } else {
                map.put("code", 500);
                map.put("msg", "手机号已存在，请直接登录!");
            }
        } else {
            if (getType) {
                map.put("code", 500);
                map.put("msg", "用户不存在，请先注册！");
            } else {
                map.put("code", 10);
                map.put("msg", getRandomCode(phoneLogNum));
            }

        }
        return map;
    }

    //    获取验证码
    public String getRandomCode(String phoneLogNum) {
        randomCode = SendMessage.getRandomCode();
        System.out.println("LoginController/getCode-phone:" + phoneLogNum + ",code:" + randomCode);
        //        发送短信
//        SendMessage.sendSms(phoneLogNum,randomCode);
        return randomCode;
    }

    //    通过手机验证码登录
    @RequestMapping(value = "/loginByP", method = RequestMethod.POST)
    public Map<String, Object> loginByPhone(String phoneLogNum, String logCode, boolean remember) {
        Map<String, Object> map = new HashMap<>();
        System.out.println("LoginController/loginByPhone:" + phoneLogNum + ",logCode:" + logCode);
        if (userService.userExist(phoneLogNum, 2)) {
            if (randomCode.equals(logCode)) {
                loginFlage = true;
                map = loginByAP(phoneLogNum, "", remember);
            } else {
                map.put("code", 500);
                map.put("msg", "验证码有误，请查看!");
            }
        } else {
            map.put("code", 500);
            map.put("msg", "用户不存在，请先注册！");
        }


        return map;
    }

    //    登出方法
    @CacheEvict(value = "abc", allEntries = true)
    @RequestMapping("/logout")
    public void logout(HttpServletResponse response) throws IOException {
        SecurityUtils.getSubject().logout();
        System.out.println("登出");
        response.sendRedirect("/xingqilin/Login.html");
    }
    
    @RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
    public ResponseEntity<String> updatePwd(String phone) {
        ResponseEntity<String> re = new ResponseEntity<String>();
        re.setData(getRandomCode(phone));
        re.setCode(1);
        return re;
    }
}
